package com.qiankan.qmsj.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.qiankan.qmsj.R;
import com.qiankan.qmsj.ushare.MyShareActivity;
import com.qiankan.qmsj.utils.MobileUtil;
import com.qiankan.qmsj.widget.TipToast;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class WebActivity extends BaseActivity {
    @BindView(R.id.tv_title)
    TextView mTitle;
    @BindView(R.id.iv_share)
    ImageView mShareView;
    @BindView(R.id.vebView)
    WebView mWebView;
    Bundle bundle;

    public static Intent newIntent(Context context, Bundle bundle) {
        Intent intent = new Intent(context, WebActivity.class);
        return intent.putExtras(bundle);
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_web;
    }

    @Override
    protected void initAllMembersView(Bundle savedInstanceState) {
        webSettings();
        bundle = getIntent().getExtras();
        String url = bundle.getString("url");
        if (bundle.getBoolean("hideShare")) {
            mShareView.setVisibility(View.INVISIBLE);
        }
        if (!TextUtils.isEmpty(bundle.getString("title"))) {
            mTitle.setText(bundle.getString("title"));
        }
        if (!url.startsWith("http")) {
            url += "http://";
        }
        if (TextUtils.isEmpty(url)) {
            finish();
        }
        loadUrl(url);
    }

    /**
     * WebView 的一些设置
     */
    private void webSettings() {
        WebSettings settings = mWebView.getSettings();
        settings.setDomStorageEnabled(true);
        settings.setJavaScriptEnabled(true);//启用支持javascript
        settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//优先使用缓存
        settings.setUseWideViewPort(true);//设置此属性，可任意比例缩放
        settings.setLoadWithOverviewMode(true);//缩放至屏幕大小
        settings.setNeedInitialFocus(true); //当webview调用requestFocus时为webview设置节点
        settings.setLoadsImagesAutomatically(true);  //支持自动加载图片
        settings.setBuiltInZoomControls(true);//支持缩放
        settings.setSupportZoom(true);//支持缩放
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//支持内容重新布局
        mWebView.setWebViewClient(new MyWebViewClient());
        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                // 监听下载功能，当用户点击下载链接的时候，直接调用系统的浏览器来下载
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });
    }

    /**
     * WebView 显示网页
     */
    private void loadUrl(String url) {
//        getWindow().setFormat(PixelFormat.TRANSLUCENT);//（这个对宿主没什么影响，建议声明）
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
//        mWebView.requestFocusFromTouch();//支持获取手势焦点，便于用户输入
        mWebView.loadUrl(url);
        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        /*mWebView.setWebViewClient(new WebViewClient() {
            //此处能拦截超链接的url,即拦截href请求的内容.
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });*/
    }

    @Override
    // 设置回退
    // 覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if (mWebView.canGoBack()) {
                mWebView.goBack(); // goBack()表示返回WebView的上一页面
                return true;
            }
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @OnClick(R.id.iv_share)
    public void onClickShare(View view) {
        startActivity(MyShareActivity.newIntent(this, bundle));
    }

    @OnClick(R.id.iv_back)
    public void onClickBack(View view) {
        finish();
    }

    //Web视图
    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url == null) {
                return true;
            } else if (url.startsWith("http") || url.startsWith("https")) {
                return super.shouldOverrideUrlLoading(view, url);
            } else if (url.startsWith("mailto:") || url.startsWith("geo:") || url.startsWith("tel:")) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);
                return true;
            } else if (url.startsWith("mqqapi://")||url.startsWith("mqqwpa://")) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, 0);
                if (list.size() > 0) {
                    startActivity(intent);
                } else {
                    TipToast.toast(WebActivity.this, "请先安装QQ");
                }
                return true;
            } else {
                if (MobileUtil.isAppInstalled(WebActivity.this, MobileUtil.yyb)) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                    return true;
                } else {
                    return super.shouldOverrideUrlLoading(view, url);
                }
            }
        }

        //重写此方法可以让webview处理https请求。
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }
    }
}
